package com.sunshine.scw.base.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * action基类
 * @author xiao
 * @version 1.0
 */
public class BaseAction extends ActionSupport {

	private static final long serialVersionUID = 434398689720082169L;

	/**
	 * 获取HttpServletRequest对象
	 * 
	 * @return HttpServletRequest
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	/**
	 * 获取request中的参数
	 * @param str 参数名
	 * @return
	 */
	protected String getParameter(String str){
		return getRequest().getParameter(str);
	}
	

	/**
	 * 获取HttpServletResponse对象
	 * 
	 * @return HttpServletResponse
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获取ServletContext对象
	 * @return ServletContext
	 */
	protected ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}

	/**
	 * 获得HttpSession对象
	 * 
	 * @param flag
	 *            如果当前session不存在是否重新创建session
	 * @return HttpSession
	 */
	protected HttpSession getSession(boolean flag) {
		return ServletActionContext.getRequest().getSession(flag);
	}

	/**
	 * 获取response输出对象
	 * 
	 * @return PrintWriter
	 * @throws IOException
	 */
	protected PrintWriter getOut() throws IOException {
		return this.getResponse().getWriter();
	}

	/**
	 * 使用response输出流输出信息
	 * 
	 * @param str
	 * @throws IOException
	 */
	protected void print(String str) throws IOException {
		this.getOut().print(str);
	}

	/**
	 * 设置request的值
	 * 
	 * @param key
	 *            设置的关键字
	 * @param obj
	 *            设置的值
	 */
	protected void setRequestAttribute(String key, Object obj) {
		this.getRequest().setAttribute(key, obj);
	}

	/**
	 * 设置session的值
	 * 
	 * @param key
	 *            设置的关键字
	 * @param obj
	 *            设置的值
	 */
	protected void setSessionAttribute(String key, Object obj) {
		this.getSession(true).setAttribute(key, obj);
	}

	/**
	 * 获得session的值
	 * 
	 * @param <T>
	 *            泛型
	 * @param key
	 *            关键字
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected <T> T getSessionAttribute(String key, Class<T> clazz) {
		return (T) this.getSession(false).getAttribute(key);
	}

}
